const { GetFromContext } = require("@/utils/gin_context");

const KEY_USER = "user:";
const KEY_DELETE = "delete:";

const optMap = {
  Article: "文章",
  BlogInfo: "博客信息",
  Category: "分类",
  Comment: "评论",
  FriendLink: "友链",
  Menu: "菜单",
  Message: "留言",
  OperationLog: "操作日志",
  Resource: "资源权限",
  Role: "角色",
  Tag: "标签",
  User: "用户",
  Page: "页面",
  // "Talk":         "说说",
  // "Login":        "登录",
  POST: "新增或修改",
  PUT: "修改",
  DELETE: "删除",
};

function GetOptString(key) {
  return optMap[key];
}

const path = [
  "Article",
  "BlogInfo",
  "Category",
  "Comment",
  "FriendLink",
  "Menu",
  "Message",
  "OperationLog",
  "Resource",
  "Role",
  "Tag",
  "User",
  "Page",
  "POST",
  "PUT",
  "DELETE",
];

const OperationLog = () => {
  return async (req, res, next) => {
    if (req.method !== "GET" && !req.path.includes("/upload")) {
      //GET请求太多，文件数据过大都不进行操作
      const uuid = GetFromContext(req, "uuid");
      let val = req.session[KEY_USER + uuid];
      let sessionInfo;
      let operationLog = {};

      if (val) {
        val = JSON.parse(val);
        sessionInfo = val;
        //找到当前匹配路由中的关键参数，如articel，tag这种去数组中匹配
        //然后再去查找对应的中文意思
        const p = req.path.split("/").find((item) => {
          for (let i = 0; i < path.length; i++) {
            path[i] = path[i].charAt(0).toLowerCase() + path[i].slice(1);
            if (item === path[i]) return item;
          }
        });

        if (p) {
          operationLog = {
            OptModule: GetOptString(p.charAt(0).toUpperCase() + p.slice(1)),
            OptType: GetOptString(req.method),
            OptUrl: req.path,
            OptMethod: req.path + req.method, //这里和go不一样
            OptDesc:
              GetOptString(req.method) +
              GetOptString(p.charAt(0).toUpperCase() + p.slice(1)),
            RequestParam: JSON.stringify(req.body), //只针对非get请求类，因此数据在body上
            RequestMethod: req.method,
            UserId: sessionInfo.userDetailDTO.LoginVO.UserInfoId,
            Nickname: sessionInfo.userDetailDTO.LoginVO.Nickname,
            IpAddress: sessionInfo.userDetailDTO.LoginVO.IpAddress,
            IpSource:
              sessionInfo.userDetailDTO.LoginVO.IpSource.country || "未知",
          };
          operationLog.ResponseData = { code: 0, message: "OK", data: null };
          operationLog.CreateAt = new Date().toLocaleString();
          operationLog.UpdateAt = new Date().toLocaleString();
          await global.mysqlPool.execute(
            `INSERT INTO operation_log (opt_module, opt_type, opt_url, opt_method, opt_desc, request_param, request_method, user_id, nickname, ip_address, ip_source, response_data, created_at, updated_at)
          VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?);
          `,
            [
              operationLog.OptModule,
              operationLog.OptType,
              operationLog.OptUrl,
              operationLog.OptMethod,
              operationLog.OptDesc,
              operationLog.RequestParam,
              operationLog.RequestMethod,
              operationLog.UserId,
              operationLog.Nickname,
              operationLog.IpAddress,
              operationLog.IpSource,
              operationLog.ResponseData,
              operationLog.CreateAt,
              operationLog.UpdateAt,
            ]
          );
        }
      }

      next();
    } else {
      next();
    }
  };
};

module.exports = OperationLog;

/* 

{
  userDetailDTO: {
    LoginVO: {
      ID: 1,
      UserInfoId: 1,
      Email: '',
      LoginType: 1,
      Username: 'admin',
      Nickname: '管理员',
      Avatar: 'https://www.bing.com/rp/ar_9isCNU2Q-VG1yEDDHnx8HAFQ.png',
      Intro: '我是管理员用户！213123123',
      Website: 'https://www.hahacode.cn',
      IpAddress: '198.16.0.2',
      IpSource: [Object],
      LastLoginTime: '2024/2/11 20:52:48',
      ArticleLikeSet: [],
      CommentLikeSet: [],
      token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsInJvbGUiOiJhZG1pbiIsInV1aWQiOiJhZWJhMjAyNjQ0OTM5OGVkZTEwZTQzMGUxMDM2YWIzNCIsImlhdCI6MTcwNzY1NTk2OCwiZXhwIjoxNzA3NzQyMzY4LCJpc3MiOiJnaW4tdnVlLWJsb2cifQ.Z5RgV9KinUgY3bpK_vjtI-3WyWkQeaQafAIetaGA53A'
    },
    Password: '$2b$10$6aVcL7Yz2V71Q2wulYbBZuuc4JwORQ2BrFKmzNMAMRGBrAC.zUs8e',
    RoleLabels: [ 'admin' ],
    IsDisable: 0,
    Browser: 'Chrome 121.0.0',
    OS: 'Windows 10.0.0'
  }
}
*/

/* 

operationLog {
  OptModule: '文章',
  OptType: '新增或修改',
  OptUrl: '/api/article',
  OptMethod: '/api/articlePOST',
  OptDesc: '新增或修改文章',
  RequestParam: '{"category_name":"测试","tag_names":["Golang"],"type":1,"is_top":0,"status":1,"title":"测试213112","content":"hello md-ed1213213123123","img":"https://cdn.hahacode.cn/1679461519cc592408198d67faf1290ff8969dc614.png","id":"36"}',
  RequestMethod: 'POST',
  UserId: 1,
  Nickname: '管理员',
  IpAddress: '198.16.0.2',
  IpSource: { country: '美国', province: '新泽西', city: '', type: '' }
}
*/
